﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Globalization;
using FRW.Common.Forms;

namespace Money.Interface
{
    public partial class ImportedTransactionsForm : Form, IProgress
    {
        public bool CancelRequest = false;

        List<Transaction> _transactions;
        InterfaceConfiguration _interfaceConfiguration;

        ImportStatus _importStatus;
        List<Transaction> _importedTransaction = new List<Transaction>();

        public GetTransactionDetailDelegate GetTransactionDetail;

        public List<Transaction> ImportedTransactions
        {
            get { return _importedTransaction; }
            set { _importedTransaction = value; }
        }

        public ImportedTransactionsForm(InterfaceConfiguration interfaceConfiguration)
        {
            _interfaceConfiguration = interfaceConfiguration;

            InitializeComponent();

            _transactionGrid.FormatRules = _interfaceConfiguration.TransactionGridFormatRules;
            _transactionGrid.GetTransactionDetail = GetTransactionDetail;

            sslFiles.Text = String.Format("{0:D3}",0);
            sslTransactions.Text = String.Format("{0:D4}", 0);
            sslSkipped.Text = String.Format("{0:D3}",0);

            this.Cursor = Cursors.WaitCursor;
        }

        private void ConfigureImportStatus(ImportStatus importStatus)
        {
            _importStatus = importStatus;

            List<Transaction> transactions = (from transaction in importStatus.ImportedTransactions orderby transaction.Date ascending select transaction).ToList();

            _transactions = importStatus.ImportedTransactions;

            _transactionGrid.DataSource = transactions;
            
            sslFiles.Text = _importStatus.ImportedFiles.Count.ToString("D3");
            sslTransactions.Text = _transactions.Count.ToString("D4");
            sslSkipped.Text = _importStatus.UnknownFiles.Count.ToString("D3");
        }

        private void btnAccept_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
            _importedTransaction = _transactions;
            Close();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            _cancelled = true;
            this.Cursor = Cursors.Default;
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
        }

        public void ImportFiles(List<string> files)
        {
        }

        private bool DoImport()
        {

            return true;
        }

        private void dgImportedTransactions_CellMouseEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
            {
                DataGridView dgv = (DataGridView)sender;

                if (e.RowIndex < dgv.Rows.Count)
                {
                    DataGridViewCell cell = dgv[e.ColumnIndex, e.RowIndex];

                    Transaction transaction = (Transaction)dgv.Rows[e.RowIndex].DataBoundItem;

                    if (GetTransactionDetail != null && transaction != null)
                    {
                        string rawText = GetTransactionDetail(transaction);
                        cell.ToolTipText = rawText;
                    }
                }
            }
        }

        private void _deleteRecords_Click(object sender, EventArgs e)
        {
            if (_transactionGrid.SelectedTransactions.Count > 0)
            {
                foreach (Transaction transaction in _transactionGrid.SelectedTransactions)
                {
                    if (transaction != null)
                    {
                        _transactions.Remove(transaction);
                    }
                }

                _transactionGrid.DataSource = null;
                _transactionGrid.DataSource = _transactions;

                sslFiles.Text = _importStatus.ImportedFiles.Count.ToString("D3");
                sslTransactions.Text = _transactions.Count.ToString("D4");
                sslSkipped.Text = _importStatus.UnknownFiles.Count.ToString("D3");
            }
        }

        private int _percentage;
        private string _progressText;
        private bool _cancelled = false;
        private object _tag;

        public new object Tag
        {
            get { return _tag; }
            set { _tag = value; }
        }

        public bool Cancelled
        {
            get { return _cancelled; }
        }

        private void UpdateStatus(Label _progressStatus, string statusMessage)
        {
            if (_progressStatus.InvokeRequired)
            {
                _progressStatus.Invoke(new Action(() => _progressStatus.Text = statusMessage));
            }
            else
            {
                if (_progressStatus.IsHandleCreated)
                {
                    _progressStatus.Text = statusMessage;
                }
            }
        }

        private void UpdateProgress(ProgressBar _progressBar, int percentage)
        {
            if (_progressBar.InvokeRequired)
            {
                _progressBar.Invoke(new Action(() => _progressBar.Value = _progressBar.Maximum * percentage / 100));
            }
            else
            {
                if (_progressBar.IsHandleCreated)
                {
                    _progressBar.Value = _progressBar.Maximum * percentage / 100;
                }
            }
        }

        public string ProgressText
        {
            get
            {
                return _progressText;
            }
            set
            {
                _progressText = value;
                UpdateStatus(_importProgressText, _progressText);
            }
        }

        public int Percentage
        {
            get
            {
                return _percentage;
            }
            set
            {
                if (value > 100)
                {
                    value = 100;
                }
                else if (value < 0)
                {
                    value = 0;
                }
                _percentage = value;
                UpdateProgress(pbImport, _percentage);
            }
        }

        public void Finished()
        {
            ImportStatus importStatus = this.Tag as ImportStatus;

            if (importStatus != null)
            {
                if (_transactionGrid.InvokeRequired)
                {
                    _transactionGrid.Invoke(new Action(() => Finished()));
                }
                else
                {
                    if (_transactionGrid.IsHandleCreated)
                    {
                        // HACK we may want to change this to use a property and then update the grid on property changing?
                        _transactionGrid.GetTransactionDetail = GetTransactionDetail;
                        ConfigureImportStatus(importStatus);
                        btnAccept.Enabled = true;
                    }
                    this.Cursor = Cursors.Default;
                }
            }

            ProgressText = "Finished Import";
        }

        private void _transactionGrid_RightClick(object sender, RightClickTransactionGridArgs e)
        {
            if (_transactionGrid.SelectedTransactions.Count > 0)
            {
                // if we right click on an unselected row then assume that we want to operate only on that row and select it
                if (_transactionGrid.SelectedTransactions.Count == 1)
                {
                    _deleteRecords.Text = "Delete Selected Transaction";
                }
                else
                {
                    _deleteRecords.Text = "Delete Selected Transactions";
                }

                _transactionContextMenu.Show(System.Windows.Forms.Cursor.Position);
            }
        }

        private void _transactionGrid_TransactionDoubleClick(object sender, TransactionGridArgs e)
        {
            Transaction transaction = e.SelectedTransaction;

            EditTransactionForm form = new EditTransactionForm();

            form.Transaction = transaction;

            if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                _transactionGrid.Refresh();
            }
        }
    }
}
